import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yi_shop/extensions/list.dart';
import 'package:yi_shop/model/cart.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class ShopCartController extends GetxController {
  RxBool isEdit = false.obs;

  RxBool isAll = false.obs;

  List<Rx<ShopCartModel>> carts = [];

  @override
  void onInit() {
    initData();
    super.onInit();
  }

  void initData() {
    var r = Random.secure();
    carts.add(Rx(ShopCartModel(
        imgUrl:
            'https://img.alicdn.com/img/i2/1129270051/O1CN01W2NQrp1CFOzkk5uKD_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
        name: '炊大皇 不粘锅 炒锅 34cm 无烟锅具 电磁炉燃气煤气灶明火通用 赠送木铲',
        attrStr: '尺码：34cm',
        price: r.nextInt(499).toDouble())));
    carts.add(Rx(ShopCartModel(
        imgUrl:
            'https://img.alicdn.com/img/i2/5585108950/O1CN01CWAWmh2Fz9iRWb24f_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
        name: '志高（CHIGO）电热水壶 304 不锈钢 双层防烫烧水壶 ZD-1898-FG9 1.8L 电',
        attrStr: '1.8L 蓝色 双层防',
        price: r.nextInt(499).toDouble())));

    carts.add(Rx(ShopCartModel(
        imgUrl:
            'https://img.alicdn.com/img/i3/488010014/O1CN01ZNIwuJ1BySSlkMJ46_!!0-saturn_solar.jpg_360x360xzq75.jpg_.webp',
        name: '   华为（HUAWEI）MateBook X 13英寸超轻薄微边框笔记本（i5-7200U 8G）',
        attrStr: '1.93kg（流光金）i5 8G+256G',
        price: r.nextInt(8999).toDouble())));
  }
}

class ShopCartPage extends GetView<ShopCartController> {
  const ShopCartPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: Text(
          '购物车',
          style: StylesUtils.customTextStyle(
            fontWeight: FontWeight.w700,
            fontSize: StylesUtils.fontSize18,
          ),
        ),
        actions: [
          TextButton(
              onPressed: () {
                controller.isEdit.value = !controller.isEdit.value;
              },
              child: Obx(() => Text(
                    controller.isEdit.isTrue ? '全选' : '编辑',
                    style: StylesUtils.customTextStyle(),
                  )))
        ],
      ),
      body: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          var row = controller.carts[index];
          return Container(
            margin: EdgeInsets.only(top: 15.h),
            color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 10.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Expanded(
                  flex: 40,
                  child: Container(
                    height: 75,
                    alignment: Alignment.center,
                    child: InkWell(
                      onTap: () {
                        row.update((val) {
                          val?.checked = !val.checked;
                        });
                        int len = controller.carts.length;
                        int max = controller.carts.filter((e) => e.value.checked).length;
                        controller.isAll.value = false;
                        if (max == len) {
                          controller.isAll.value = true;
                        }
                      },
                      child: Obx(() => row.value.checked
                          ? SvgUtils.assetName('u15376', width: 22, height: 22)
                          : Container(
                              constraints: const BoxConstraints.expand(width: 22, height: 22),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15),
                                  border: Border.all(
                                      color: ColorsUtils.parseColorFromHexString(
                                          ColorsUtils.color9999))),
                            )),
                    ),
                  ),
                ),
                Expanded(
                  flex: 80,
                  child: CachedNetworkImage(
                    imageUrl: row.value.imgUrl,
                    width: 80,
                    height: 75,
                    fit: BoxFit.fill,
                  ),
                ),
                Expanded(
                  flex: (Get.width - 120).toInt(),
                  child: Container(
                    padding: const EdgeInsets.only(left: 10, right: 15),
                    child: Column(
                      children: [
                        Container(
                          alignment: Alignment.topLeft,
                          child: Text(
                            row.value.name,
                            style: StylesUtils.customTextStyle(
                                fontSize: StylesUtils.fontSize12,
                                color: ColorsUtils.color3333,
                                lineHeight: 1.3.h),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 5, bottom: 10),
                          alignment: Alignment.centerLeft,
                          child: Text(
                            row.value.attrStr,
                            style: StylesUtils.customTextStyle(
                                fontSize: StylesUtils.fontSize12, color: ColorsUtils.color9999),
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '￥${row.value.price}',
                              style: StylesUtils.customTextStyle(
                                color: ColorsUtils.colorF95e,
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                            Wrap(
                              crossAxisAlignment: WrapCrossAlignment.center,
                              alignment: WrapAlignment.end,
                              spacing: 0,
                              children: [
                                InkWell(
                                  onTap: () {
                                    if (row.value.num > 1) {
                                      row.update((val) {
                                        val?.num--;
                                      });
                                    }
                                  },
                                  child: Container(
                                    constraints: const BoxConstraints.expand(width: 27, height: 27),
                                    decoration: BoxDecoration(
                                        border: Border.all(
                                            color: ColorsUtils.parseColorFromHexString(
                                                ColorsUtils.colorCccc))),
                                    alignment: Alignment.center,
                                    child: Text(
                                      '➖',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color3333,
                                          fontSize: StylesUtils.fontSize13),
                                    ),
                                  ),
                                ),
                                Container(
                                  constraints: const BoxConstraints.expand(width: 40, height: 27),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
                                      border: Border(
                                    top: BorderSide(
                                        color: ColorsUtils.parseColorFromHexString(
                                            ColorsUtils.colorCccc)),
                                    bottom: BorderSide(
                                        color: ColorsUtils.parseColorFromHexString(
                                            ColorsUtils.colorCccc)),
                                  )),
                                  child: AnimatedSwitcher(
                                    duration: const Duration(milliseconds: 500),
                                    transitionBuilder: (Widget child, Animation<double> animation) {
                                      //执行缩放动画
                                      return ScaleTransition(scale: animation, child: child);
                                    },
                                    child: Obx(() => Text('${row.value.num}',
                                        key: ValueKey<int>(row.value.num),
                                        style: StylesUtils.customTextStyle(
                                            fontSize: StylesUtils.fontSize12,
                                            color: ColorsUtils.color0000))),
                                  ),
                                ),
                                InkWell(
                                  onTap: () {
                                    row.update((val) {
                                      val?.num++;
                                    });
                                  },
                                  child: Container(
                                    constraints: const BoxConstraints.expand(width: 27, height: 27),
                                    decoration: BoxDecoration(
                                        border: Border.all(
                                            color: ColorsUtils.parseColorFromHexString(
                                                ColorsUtils.colorCccc))),
                                    alignment: Alignment.center,
                                    child: Text(
                                      '➕',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color3333,
                                          fontSize: StylesUtils.fontSize13),
                                    ),
                                  ),
                                )
                              ],
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        },
        itemCount: controller.carts.length,
      ),
      bottomNavigationBar: SafeArea(
        bottom: true,
        child: Container(
          height: 50,
          color: Colors.white,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 50,
                alignment: Alignment.centerLeft,
                padding: const EdgeInsets.only(left: 10),
                child: Obx(() => TextButton(
                      onPressed: () {
                        controller.isAll.value = !controller.isAll.value;
                        for (var element in controller.carts) {
                          element.value.checked = controller.isAll.value;
                        }
                      },
                      style: const ButtonStyle(
                        alignment: Alignment.center,
                      ),
                      child: RichText(
                        text: TextSpan(children: [
                          WidgetSpan(
                              child: controller.isAll.isTrue
                                  ? SvgUtils.assetName('u15376', width: 22, height: 22)
                                  : Container(
                                      constraints:
                                          const BoxConstraints.expand(width: 22, height: 22),
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(15),
                                          border: Border.all(
                                              color: ColorsUtils.parseColorFromHexString(
                                                  ColorsUtils.color9999))),
                                    ),
                              alignment: PlaceholderAlignment.middle),
                          TextSpan(
                            text: '  全选',
                            style: StylesUtils.customTextStyle(
                              color: ColorsUtils.color6666,
                            ),
                          ),
                        ]),
                      ),
                    )),
              ),
              Expanded(child: Obx(() {
                if (controller.isEdit.isTrue) {
                  return Container(
                    height: 50,
                    alignment: Alignment.center,
                    child: Wrap(
                      spacing: 20,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      alignment: WrapAlignment.center,
                      children: [
                        TextButton(
                            onPressed: () {},
                            style: ButtonStyle(
                                minimumSize: const MaterialStatePropertyAll(Size(87, 30)),
                                shape: MaterialStatePropertyAll(RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5.r))),
                                side: MaterialStatePropertyAll(BorderSide(
                                    color: ColorsUtils.parseColorFromHexString(
                                        ColorsUtils.color7979))),
                                alignment: Alignment.center),
                            child: Text(
                              '关注',
                              style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333,
                                fontSize: StylesUtils.fontSize13,
                              ),
                            )),
                        TextButton(
                            onPressed: () {},
                            style: ButtonStyle(
                                minimumSize: const MaterialStatePropertyAll(Size(87, 30)),
                                shape: MaterialStatePropertyAll(RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(5.r))),
                                side: MaterialStatePropertyAll(BorderSide(
                                    color: ColorsUtils.parseColorFromHexString(
                                        ColorsUtils.color7979))),
                                alignment: Alignment.center),
                            child: Text(
                              '删除',
                              style: StylesUtils.customTextStyle(
                                color: ColorsUtils.color3333,
                                fontSize: StylesUtils.fontSize13,
                              ),
                            )),
                      ],
                    ),
                  );
                }
                return Container(
                  height: 50,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '合计：￥$totalPrice',
                    style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize16, color: ColorsUtils.color3333),
                  ),
                );
              })),
              Obx(() => Offstage(
                  offstage: controller.isEdit.isTrue,
                  child: TextButton(
                      onPressed: () {},
                      style: ButtonStyle(
                        fixedSize: const MaterialStatePropertyAll(Size(120, 50)),
                        backgroundColor: MaterialStatePropertyAll(
                            ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
                        shape: const MaterialStatePropertyAll(
                          LinearBorder(),
                        ),
                        alignment: Alignment.center,
                      ),
                      child: Text(
                        '去结算 ($lenCart)',
                        style: StylesUtils.customTextStyle(),
                      ))))
            ],
          ),
        ),
      ),
    );
  }

  int get lenCart {
    return controller.carts.filter((e) => e.value.checked).length;
  }

  double get totalPrice {
    double total = 0.0;
    controller.carts.filter((e) => e.value.checked).forEach((element) {
      total += element.value.price * element.value.num;
    });
    return total;
  }
}
